﻿@page "/"
@using System.Reflection

<MudLayout>
    <MudAppBar Position="Position.Absolute" Elevation="0">
        <MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Inherit" Edge="Edge.Start" OnClick="@((e) => DocsDrawerToggle())" />
        <MudText Typo="Typo.h6">@selectedType?.Name</MudText>
        <MudAppBarSpacer />
    </MudAppBar>
    <MudDrawer Open="@drawerOpen">
        <MudDrawerHeader>
            <MudText Typo="Typo.h6">TestComponents</MudText>
        </MudDrawerHeader>
        <MudList>
            @foreach (var type in getTestComponenTypes().OrderBy(x=>x.Name))
            {
                <MudListItem OnClick="@(() => selectedType = type)" @key="type.Name">@type.Name</MudListItem>    
            }
        </MudList>
    </MudDrawer>
    <MudMainContent>
        
        <MudText Style="padding-left: 24px; margin-left: 24px;">
            @getDescription(selectedType)
        </MudText>
        <MudPaper Elevation="5" Style="padding: 24px; margin: 24px;">
            @if (@selectedType == null)
            {
                <span>Select a component</span>
            }
            else
            {
                @TestComponent()
            }
        </MudPaper>

    </MudMainContent>
</MudLayout>

@code {
    bool drawerOpen = true;
    Type selectedType = null;

    void DocsDrawerToggle()
    {
        drawerOpen = !drawerOpen;
    }

    RenderFragment TestComponent() => builder =>
    {
        builder.OpenComponent(0, selectedType);
        //builder.AddAttribute(1, "Title", "Some title");
        builder.CloseComponent();
    };

    IEnumerable<Type> getTestComponenTypes()
    {
        foreach (var type in typeof(Program).Assembly.GetTypes())
        {
            if (!type.Name.Contains("Test"))
                continue;
            if (type.Name.StartsWith("<"))
                continue;
            if (!type.GetInterfaces().Contains(typeof(IComponent)))
                continue;
            yield return type;
        }
        //foreach (var type in typeof(MudBlazor.Docs.Components.DocsPage).Assembly.GetTypes())
        //{
        //    if (!type.Name.EndsWith("Example"))
        //        continue;
        //    if (type.Name.StartsWith("<"))
        //        continue;
        //    yield return type;
        //}
    }

    private string getDescription(Type type)
    {
        if (type == null)
            return "";
        try
        {
            var field = type.GetField("__description__", BindingFlags.Public | BindingFlags.Static | BindingFlags.GetField);
            return (string)field.GetValue(null);
        }
        catch (Exception)
        {
            return "Description not found.";
        }
    }

}